import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'
import { streamChat, fetchConversations, fetchMessages, stopGeneration } from '@/api/dify'
import { Conversation, Message,SendMessageParams } from '@/types/dify'
@Module({ namespaced: true, name: 'difyChat' })
export default class DifyChatModule extends VuexModule {
  // State
  activeConversation: Conversation | null = null
  messages: Message[] = []
  conversations: Conversation[] = []
  isSending = false
  currentTaskId = ''
  userId = 'default-user' // 根据实际用户系统替换

  // Getters
  get hasActiveConversation(): boolean {
    return !!this.activeConversation?.id
  }

  // Mutations
  @Mutation
  SET_CONVERSATION(conversation: Conversation | null) {
    this.activeConversation = conversation
  }

  @Mutation
  ADD_MESSAGE(message: Message) {
    this.messages.push(message)
  }

  @Mutation
  UPDATE_MESSAGE({ id, chunk }: { id: string; chunk: string }) {
    const message = this.messages.find(m => m.id === id)
    if (message) {
      message.answer += chunk
    }
  }

  @Mutation
  SET_CONVERSATIONS(conversations: Conversation[]) {
    this.conversations = conversations
  }

  @Mutation
  SET_SENDING(status: boolean) {
    this.isSending = status
  }

  @Mutation
SET_MESSAGES(messages: Message[]) {
  this.messages = messages
}

  // Actions
  @Action
  async sendMessage(payload: SendMessageParams) {
    this.SET_SENDING(true)
    
    try {
      const es = streamChat(payload, this.userId, {
      
        onMessage: (event) => {
           let existing:any = false;
          switch (event.event) {
            case 'message':
              if (!event.message_id) return
              
              existing = this.messages.find(m => m.id === event.message_id)
              if (!existing) {
                this.ADD_MESSAGE({
                  id: event.message_id,
                  conversation_id: event.conversation_id || '',
                  query: payload.query,
                  answer: event.answer || '',
                  files: [],
                  created_at: Date.now()
                })
              } else {
                this.UPDATE_MESSAGE({
                  id: event.message_id,
                  chunk: event.answer || ''
                })
              }
              break

            case 'message_end':
              this.SET_SENDING(false)
              es.close()
              break

            case 'error':
              throw new Error(event.message || 'Unknown error')
          }
        },
        onError: (error) => {
          this.SET_SENDING(false)
          console.error('Stream error:', error)
        },
        onEnd: () => {
          this.SET_SENDING(false)
        }
      })
    } catch (error) {
      this.SET_SENDING(false)
      console.error('Message send failed:', error)
    }
  }

  @Action
  async loadConversations() {
    const conversations = await fetchConversations(this.userId)
    this.SET_CONVERSATIONS(conversations)
  }

  @Action
  async selectConversation(conversationId: string | null) {
    if (!conversationId) {
      this.SET_CONVERSATION(null)
      this.SET_MESSAGES([])
      return
    }

    const messages = await fetchMessages(conversationId, this.userId)
    const conversation = this.conversations.find(c => c.id === conversationId)
    
    if (conversation) {
      this.SET_CONVERSATION(conversation)
      this.SET_MESSAGES( messages)
    }
  }

  @Action
  async stopCurrentGeneration() {
    if (this.currentTaskId) {
      await stopGeneration(this.currentTaskId, this.userId)
    }
  }
}